package server.io.game.conn;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.HashMap;

import server.io.client.ClientInfo;

public class AcptServer_K extends AcceptThread
{

	private Selector serverSelector = null;
	private int serverPort;
	
	// 一个大厅监听器
	private RecvServer_K recvListener = null;
	// 玩家Id
	private int ID = 1000;

	public AcptServer_K(int argPort)
	{
		this.serverPort = argPort;

	}

	public void init()
	{
		recvListener = new RecvServer_K();
	}

	@Override
	public void run()
	{
		try
		{
			// 生成一个监听端
			ServerSocketChannel mainServerChannel = ServerSocketChannel
					.open();
			// 将监听端设为异步方式
			mainServerChannel.configureBlocking(false);
			// 生成一个信号监视器
			serverSelector = Selector.open();
			// 侦听端绑定到一个端口
			mainServerChannel.socket().bind(
					new InetSocketAddress(serverPort));
			// 设置侦听端所选的异步信号OP_ACCEPT
			mainServerChannel.register(serverSelector,
					SelectionKey.OP_ACCEPT);
			
			recvListener.start();
			recvListener.setHallId(1);

			System.out.println(" Server start .. ! ");

			while (true)
			{
				int n = serverSelector.select();
				if (n == 0)
				{
					continue;
				}
				for (SelectionKey key : serverSelector
						.selectedKeys())
				{
					serverSelector.selectedKeys().remove(key);

					if (key.isAcceptable())
					{
						System.out.println("One Acceptable Connect..!");
						pickSocketChannel(key);
					}
				}
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	private void pickSocketChannel(SelectionKey argKey)
	{
		// 接受一个新的连接
		SocketChannel one_new_channel = null;
		try
		{
			// 侦听端信号触发
			ServerSocketChannel oneNewServerChannel = (ServerSocketChannel) argKey
					.channel();
			one_new_channel = oneNewServerChannel.accept();

		} catch (IOException e)
		{
			e.printStackTrace();
		}
		ClientInfo client = makeCustom(one_new_channel);
		// 接收到新连接后放入大厅,1代表新连接的channel,绑定进大厅
		recvListener.setUserInHall(one_new_channel, -1);
		
	}
	
	private ClientInfo makeCustom(SocketChannel argSc)
	{
		ClientInfo user = new ClientInfo();
		user.channel = argSc;
		user.clientId = ID;
		ID++;
		return user;
	}
}